<script setup lang="ts">
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
// import { useDetail } from "@/views/brokerAdmin/hooks";
import {
  ref,
  reactive,
  computed,
  defineEmits,
  defineOptions,
  watch,
  defineProps,
  onMounted
} from "vue";
import { useRouter } from "vue-router";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { debounce } from "lodash";
// import { brokerList } from "@/api/broker";
// import { getOrderStatusList, getOrderTypeList } from "@/api/entrust";
// import { rechargeStatusList } from "@/api/recharge";
// import { withdrawStatusList } from "@/api/withdraw";
// import { agentMoneyLogType } from "@/api/capital";
// import { myCommissionType } from "@/api/brokerage";
import { message } from "@/utils/message";

// const router = useRouter();
// const { toDetail, router } = useDetail();
defineOptions({
  name: "ReHeaderSearch"
});
// 定义 Props 类型
interface Props {
  tableType: string;
}
const props = withDefaults(defineProps<Props>(), {
  tableType: ""
});

// 定义事件
const emit = defineEmits(["search"]);
// 定义查询表单数据
const queryForm = reactive({
  account: "", // 账号
  mobile: "", // 手机号
  superiors_id: "", // 上级ID
  superiors_mobile: "", // 上级手机号
  user_id: "", // 用户ID
  level: "", // 等级
  start_time: "", // 开始时间
  end_time: "", // 截至时间
  virtual: "", // 虚拟
  agency: "", // 代理
  goods_name: "", // 商品名
  all_type: "", // 商品类型
  blind_box_id: "", // 盲盒ID
  give_user_id: "", // 转增用户ID
  belong_to_user_id: "", // 所属用户ID
  memo: "", // 备注
  user_coupon_status: "" // 优惠券使用状态
});

// 定义选项
const levelOptions = reactive([
  {
    label: "全部等级",
    value: 0
  },
  {
    label: "普通玩家",
    value: 1
  },
  {
    label: "黄金代理",
    value: 2
  },
  {
    label: "白银代理",
    value: 3
  }
]);
const virtualOptions = reactive([
  {
    label: "全部",
    value: 0
  },
  {
    label: "是",
    value: 1
  },
  {
    label: "否",
    value: 2
  }
]);

const agencyOptions = reactive([
  {
    label: "全部",
    value: 0
  },
  {
    label: "是",
    value: 1
  },
  {
    label: "否",
    value: 2
  }
]);
const allTypeOptions = reactive([
  {
    label: "开苹果14Pro ，100%有奖",
    value: 0
  },
  {
    label: "Apple全家桶！高爆",
    value: 1
  },
  {
    label: "低价尝鲜—生活好物",
    value: 2
  },
  {
    label: "99高爆-生活家电",
    value: 3
  }
]);
const userCouponStatusOptions = reactive([
  {
    label: "未使用",
    value: 0
  },
  {
    label: "已使用",
    value: 1
  }
]);
// const brokerOptions = reactive([]);

const directionOptions = reactive([]);

const statusOptions = reactive([]);
const payStatusOptions = reactive([]);
const cashStatusOptions = reactive([]);
const changeTypeOptions = reactive([]);
const incomeTypeOptions = reactive([]);
// 权限数据示例
const userPermissions = ref([
  "account",
  "mobile",
  "superiors_id",
  "superiors_mobile",
  "user_id",
  "level",
  "start_time",
  "end_time",
  "virtual",
  "agency",
  "goods_name",
  "all_type",
  "blind_box_id",
  "give_user_id",
  "belong_to_user_id",
  "memo",
  "user_coupon_status"
]);

// 根据权限显示字段
const visibleFields = computed(() => {
  const allFields = {
    account: {
      label: "账号",
      component: "el-input",
      placeholder: "请输入账号"
      // type: "number"
    },
    mobile: {
      label: "手机号",
      component: "el-input",
      placeholder: "请输入手机号",
      type: "number",
      isMobile: true
    },
    superiors_id: {
      label: "上级ID",
      component: "el-input",
      placeholder: "请输入上级ID",
      type: "number"
    },
    superiors_mobile: {
      label: "上级手机号",
      component: "el-input",
      placeholder: "请输入上级手机号",
      type: "number",
      isMobile: true
    },
    user_id: {
      label: "用户ID",
      component: "el-input",
      placeholder: "用户ID",
      type: "number"
    },
    level: {
      label: "等级",
      component: "el-select",
      options: levelOptions,
      placeholder: "请选择等级"
    },
    start_time: {
      label: "开始时间",
      component: "el-date-picker",
      placeholder: "年-月-日"
    },
    end_time: {
      label: "结束时间",
      component: "el-date-picker",
      placeholder: "年-月-日"
    },
    virtual: {
      label: "虚拟",
      component: "el-select",
      options: virtualOptions,
      placeholder: "请选择是否虚拟"
    },
    agency: {
      label: "代理",
      component: "el-select",
      options: agencyOptions,
      placeholder: "请选择是否代理"
    },
    goods_name: {
      label: "商品名",
      component: "el-input",
      placeholder: "请输入商品名"
      // type: "number"
    },
    all_type: {
      label: "商品类型",
      component: "el-select",
      options: allTypeOptions,
      placeholder: "请选择商品类型"
    },
    blind_box_id: {
      label: "盲盒ID",
      component: "el-input",
      placeholder: "请输入盲盒ID",
      type: "number"
    },
    give_user_id: {
      label: "转增用户ID",
      component: "el-input",
      placeholder: "请输入转增用户ID",
      type: "number"
    },
    belong_to_user_id: {
      label: "所属用户ID",
      component: "el-input",
      placeholder: "请输入用户ID进行查询",
      type: "number"
    },
    memo: {
      label: "备注",
      component: "el-input",
      placeholder: "请输入备注"
    },
    user_coupon_status: {
      label: "使用状态",
      component: "el-select",
      options: userCouponStatusOptions,
      placeholder: "请选择使用状态"
    }
  };
  // return Object.entries(allFields).filter(([key]) => userPermissions.value.includes(key));
  return userPermissions.value
    .map(key => [key, allFields[key]])
    .filter(([key, value]) => value);
});

// 防抖搜索函数
const handleEmitSearch = debounce(() => {
  emit("search", queryForm);
}, 300);
// 新增经纪人
const handleCreateBroker = debounce(() => {
  // const routeData = {
  //   path: "/brokerAdmin/create",
  //   name: "createBroker",
  //   title: "添加经纪人"
  // };
  // toDetail({ routeData: JSON.stringify(routeData) }, "query");
  // useMultiTagsStoreHook().handleTags("push", {
  //   path: `/brokerAdmin/create`,
  //   name: "createBroker",
  //   meta: {
  //     // 如果使用的是非国际化精简版title可以像下面这么写
  //     title: `添加经纪人`,
  //     // 最大打开标签数
  //     dynamicLevel: 3
  //   }
  // });
  // router.push({ name: "createBroker" });
});
onMounted(() => {
  handleEmitSearch();
});
// 动态修改 userPermissions
const updatePermissions = type => {
  console.log("updatePermissions", type);
  switch (type) {
    case "clientList": // 客户列表
      userPermissions.value = [
        "account",
        "mobile",
        "superiors_id",
        "superiors_mobile",
        "user_id",
        "level",
        "start_time",
        "end_time",
        "virtual",
        "agency"
      ]; // 只显示这几个字段,字段顺序代表输入框的位置
      break;
    case "shopList": // 商品列表
      userPermissions.value = ["goods_name"];
      break;
    case "blindBoxGoodsList": // 盲盒商品列表
      userPermissions.value = ["all_type"];
      break;
    case "lotteryRecordList": // 中奖记录
      userPermissions.value = [
        "account",
        "user_id",
        "blind_box_id",
        "superiors_mobile"
      ];
      break;
    case "giveRecordList": // 转增记录
      userPermissions.value = ["give_user_id"];
      break;
    case "capitalRecordList": // 资金记录
      userPermissions.value = [
        "start_time",
        "end_time",
        "belong_to_user_id",
        "account",
        "memo",
        "superiors_mobile",
        "virtual"
      ];
      break;
    case "withdrawRecordList": // 提现记录
      userPermissions.value = ["start_time", "end_time", "account", "user_id"];
      break;
    case "userCouponList": // 用户优惠券列表
      userPermissions.value = ["user_coupon_status", "account"];
      break;
    case "userAddressList": // 用户地址列表
      userPermissions.value = ["account", "user_id"];
      break;
    case "position": // 持仓查询
      userPermissions.value = [
        "stockCode",
        "broker",
        "mobile",
        "username",
        "position_id"
        // "account"
      ]; // 只显示这几个字段,字段顺序代表输入框的位置
      break;
    case "entrust": // 委托查询
      userPermissions.value = [
        "stockCode",
        "mobile",
        "username",
        // "account",
        "broker",
        "direction",
        "start_entrust_time",
        "end_entrust_time",
        "position_id",
        "status"
      ]; // 只显示这几个字段,字段顺序代表输入框的位置
      break;
    case "transaction": // 成交查询
      userPermissions.value = [
        "stockCode",
        "mobile",
        "username",
        "trading_day",
        "direction",
        "broker",
        "start_trading_time",
        "end_trading_time",
        "position_id",
        "entrust_id"
        // "account"
      ]; // 只显示这几个字段,字段顺序代表输入框的位置
      break;
    case "close": // 平仓查询
      userPermissions.value = [
        "stockCode",
        "broker",
        "mobile",
        "username",
        "position_id",
        // "account",
        "start_close_time",
        "end_close_time"
      ]; // 只显示这几个字段,字段顺序代表输入框的位置
      break;
    case "user": // 用户列表
      userPermissions.value = ["mobile", "username", "broker"];
      break;
    case "recharge": // 充值记录
      userPermissions.value = [
        "pay_status",
        "mobile",
        "username",
        "start_recharge_time",
        "end_recharge_time"
      ];
      break;
    case "withdraw": // 提现记录
      userPermissions.value = [
        "cash_status",
        "mobile",
        "username",
        "start_apply_time",
        "end_apply_time"
      ];
      break;
    case "broker": // 经纪人列表
      userPermissions.value = ["mobile"];
      break;
    case "capital": //资金明细
      // userPermissions.value = ["change_time", "change_type"];
      userPermissions.value = ["change_time", "income_type"];
      break;
    case "brokerage": // 我的佣金
      userPermissions.value = [
        "mobile",
        "broker",
        "income_type",
        "start_time",
        "end_time"
      ];
      break;
  }
};
watch(
  () => props.tableType,
  (newVal, oldVal) => {
    updatePermissions(newVal);
    // 如果是持仓列表,需要获取经纪人数据
    // switch (newVal) {
    //   case "position":
    //     getBrokerOptions();
    //     break;
    //   case "entrust":
    //     getBrokerOptions();
    //     getDirectionOptions();
    //     getOrderStatusOptions();
    //     break;
    //   case "transaction":
    //     getBrokerOptions();
    //     getDirectionOptions();
    //     break;
    //   case "close":
    //   case "user":
    //     getBrokerOptions();
    //     break;
    //   case "recharge":
    //     getRechargeStatusOptions();
    //     break;
    //   case "withdraw":
    //     getWithdrawStatusOptions();
    //     break;
    //   case "capital":
    //     // getCapitalChangeTypeOptions();
    //     getCommissionTypeOptions();
    //     break;
    //   case "brokerage":
    //     getBrokerOptions();
    //     getCommissionTypeOptions();
    //     break;
    // }
  },
  {
    deep: true,
    immediate: true
  }
);
const inputSize = ref("small" as const);
// 限制手机号长度
const handleInputMobile = (e: any) => {
  const maxlength = 11;
  if (e.target.value.length > maxlength) {
    e.target.value = e.target.value.slice(0, maxlength);
  }
};

// 获取经纪人列表
// async function getBrokerOptions() {
//   brokerOptions.splice(0, brokerOptions.length);
//   const res = await brokerList();
//   if (res.code == 1) {
//     if (res.data?.data.length > 0) {
//       const data = res.data.data.map(item => {
//         return {
//           label: item.broker_name,
//           value: item.id
//         };
//       });
//       brokerOptions.push(...data);
//     }
//   } else {
//     message(res.data.msg, { customClass: "el", type: "error" });
//   }
// }
// 获取委托列表-方向接口
// async function getDirectionOptions() {
//   try {
//     const res = await getOrderTypeList();
//     if (res.code !== 1) {
//       throw new Error(res.data.msg || "获取数据失败");
//     }
//     const result = res.data;
//     const data = [];
//     for (var key in result) {
//       data.push({ label: result[key], value: key });
//     }
//     directionOptions.splice(0, directionOptions.length, ...data);
//   } catch (error) {
//     message(error.message, { customClass: "el", type: "error" });
//   }
// }

// 获取委托列表-状态接口
// async function getOrderStatusOptions() {
//   try {
//     const res = await getOrderStatusList();
//     if (res.code !== 1) {
//       throw new Error(res.data.msg || "获取数据失败");
//     }
//     const result = res.data;
//     const data = [];
//     for (var key in result) {
//       data.push({ label: result[key], value: key });
//     }
//     // 清空 statusOptions 数组并添加新数据
//     statusOptions.splice(0, statusOptions.length, ...data);
//   } catch (error) {
//     message(error.message, { customClass: "el", type: "error" });
//   }
// }
// 获取充值记录-支付状态
// async function getRechargeStatusOptions() {
//   try {
//     const res = await rechargeStatusList();
//     if (res.code !== 1) {
//       throw new Error(res.data.msg || "获取数据失败");
//     }
//     const result = res.data;
//     const data = [];
//     for (var key in result) {
//       data.push({ label: result[key], value: key });
//     }
//     // 清空 statusOptions 数组并添加新数据
//     payStatusOptions.splice(0, payStatusOptions.length, ...data);
//   } catch (error) {
//     message(error.message, { customClass: "el", type: "error" });
//   }
// }

// 获取提现记录-状态
// async function getWithdrawStatusOptions() {
//   try {
//     const res = await withdrawStatusList();
//     if (res.code !== 1) {
//       throw new Error(res.data.msg || "获取数据失败");
//     }
//     const result = res.data;
//     const data = [];
//     for (var key in result) {
//       data.push({ label: result[key], value: key });
//     }
//     // 清空 statusOptions 数组并添加新数据
//     cashStatusOptions.splice(0, cashStatusOptions.length, ...data);
//   } catch (error) {
//     message(error.message, { customClass: "el", type: "error" });
//   }
// }
// 获取资金明细变动类型
// async function getCapitalChangeTypeOptions() {
//   try {
//     const res = await agentMoneyLogType();
//     if (res.code !== 1) {
//       throw new Error(res.data.msg || "获取数据失败");
//     }
//     const result = res.data;
//     const data = [];
//     for (var key in result) {
//       data.push({ label: result[key], value: key });
//     }
//     // 清空 statusOptions 数组并添加新数据
//     changeTypeOptions.splice(0, changeTypeOptions.length, ...data);
//   } catch (error) {
//     message(error.message, { customClass: "el", type: "error" });
//   }
// }

// 获取我的佣金收入类型
// async function getCommissionTypeOptions() {
//   try {
//     const res = await myCommissionType();
//     if (res.code !== 1) {
//       throw new Error(res.data.msg || "获取数据失败");
//     }
//     const result = res.data;
//     const data = [];
//     for (var key in result) {
//       data.push({ label: result[key], value: key });
//     }
//     // 清空 statusOptions 数组并添加新数据
//     incomeTypeOptions.splice(0, incomeTypeOptions.length, ...data);
//   } catch (error) {
//     message(error.message, { customClass: "el", type: "error" });
//   }
// }
</script>
<template>
  <div class="entrust-container">
    <el-card shadow="never" class="mb-2">
      <el-row :gutter="24">
        <template
          v-for="([key, field], index) in visibleFields"
          :key="key + index"
        >
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <div class="p-2 rounded header-form-item">
              <div class="label">{{ field.label }}:</div>
              <component
                :is="field.component"
                v-if="
                  field.component === 'el-input' ||
                  field.component === 'el-date-picker'
                "
                v-model="queryForm[key]"
                :type="field.type || 'text'"
                :oninput="field.isMobile ? handleInputMobile : null"
                :size="inputSize"
                :placeholder="field.placeholder"
              />
              <el-select
                v-else
                v-model="queryForm[key]"
                :size="inputSize"
                filterable
                clearable
                :placeholder="field.placeholder"
              >
                <el-option
                  v-for="item in field.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-col>
        </template>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <div class="p-2 rounded header-form-item">
            <el-button
              :size="inputSize"
              type="primary"
              :icon="useRenderIcon('ep:search')"
              @click="handleEmitSearch"
              >筛选</el-button
            >
            <el-button
              v-if="tableType == 'broker'"
              :size="inputSize"
              type="primary"
              :icon="useRenderIcon('ep:circle-plus')"
              @click="handleCreateBroker"
              >添加经纪人</el-button
            >
          </div>
        </el-col>
      </el-row>
      <!--      <el-row>-->
      <!--        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
      <!--          <div class="p-2 rounded header-form-item">-->
      <!--            <el-button type="primary" @click="updatePermissions"-->
      <!--              >更新权限</el-button-->
      <!--            >-->
      <!--          </div>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
    </el-card>
  </div>
</template>
